<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="js/resources/css/ext-all.css"
	type="text/css"></link>
<link rel="stylesheet" href="css/main.css"
	type="text/css"></link>
<script type="text/javascript" src="js/ext-all-debug.js"></script>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">

	Ext.require([ 
        'Ext.form.*', 
        'Ext.data.*', 
        'Ext.grid.*',
		'Ext.layout.container.Column',     
		'Ext.toolbar.Paging',
	    //'Ext.ux.PreviewPlugin',
	    'Ext.ModelManager',
	    'Ext.tip.QuickTipManager' 
	]);
	
	Ext.onReady(function() {
		Ext.QuickTips.init();
		var bd = Ext.getBody();
		
		// Define the model for a State
		Ext.define('pageSize', {
			extend: 'Ext.data.Model',
		    fields: [
		        {type: 'int', name: 'size'},
		    ]
		});
		
		var pageSizeData = [
			{"size": 15},
			{"size": 25},
			{"size": 50},
			{"size": 100},
        ];

		// The data store holding the states
		var pageStore = Ext.create('Ext.data.Store', {
		    model: 'pageSize',
		    data: pageSizeData
		});

		// Simple ComboBox using the data store
		var pageSizeCombo = Ext.create('Ext.form.field.ComboBox', {
			id: 'pgCmb',
		    fieldLabel: 'Rows/Page',
		    //renderTo: 'simpleCombo',
		    displayField: 'size',
		    width: 130,
		    labelWidth: 70,
		    margin: '0 0 0 20',
		    store: pageStore,
		    queryMode: 'local',
		    //typeAhead: true,
		    //forceSelection: true
		    allowBlank : false,
		    editable: false,
		    value: 25,
		    listeners:{
		         'change': function(pgCmb, newValue, oldValue, eOpts) {
		        	 //alert(newValue+ ', ' + oldValue)
		        	 
		        	 store.pageSize=newValue;
		        	 store.loadPage(1, {callback: callback});
		         }
		    }
		});
		
		Ext.define('hourModel', {
			extend: 'Ext.data.Model',
		    fields: [
		        {name: 'hour'},
		        {name: 'index'}
		    ]
		});
		
		/*
		var pageSizeData = [
			{"size": 15},
			{"size": 25},
			{"size": 50},
			{"size": 100},
        ];
		*/

		// The data store holding the states
		var hourStore = Ext.create('Ext.data.Store', {
			//baseParams: { selDate: '2011-02-22' },
			//pageSize: 10,
			model: 'hourModel',
			
			proxy: {
			    type: 'ajax',
			    url: 'hourlyFraudSummary!getHour.action',
			    //url: "gridtest.json",
			    reader: {
			        type: 'json',
			        totalProperty: 'total',
			        root: 'root'
			    }
			}
		 	//autoLoad: true
		});
		
		hourStore.on('beforeload', function (store, options) {
	        var new_params = { 
	        		selDate: Ext.getCmp('df').getRawValue(), 
	        };
	        Ext.apply(store.proxy.extraParams, new_params);
	        Ext.getCmp("gridForm").getEl().mask("Loading");
	        // alert('beforeload');
	    });
		
		var callback = function(r, options, success) {
			Ext.getCmp("gridForm").getEl().unmask();
			if(success) {
				if(r.length>0) {
					showExportIcon();
				} else {
					hideExportIcon();
				}
			} else {
				Ext.Msg.alert('Error', 'Data Loading Failed!');
				store.removeAll();
				hideExportIcon();
			} 
		};
		
		var hourCallback = function(r, options, success) {
			Ext.getCmp("gridForm").getEl().unmask();
			if(success) {
				if(r.length>0) {
					showHourCmb();
					showExportIcon();
					var hourCombo=Ext.getCmp('hourCmb');
					hourCombo.setValue(0);
					hourCombo.fireEvent('change');
				} else {
					hideHourCmb();
					hideExportIcon();
				}
			} else {
				Ext.Msg.alert('Error', 'Data Loading Failed!');
				store.removeAll();
				hideHourCmb();
				hideExportIcon();
			} 
		};
		
		function hideHourCmb() {
			Ext.getCmp('hourCmb').hide();
		}
		
		function showHourCmb() {
			Ext.getCmp('hourCmb').show();
		}

		// Simple ComboBox using the data store
		var hourCombo = Ext.create('Ext.form.field.ComboBox', {
			id: 'hourCmb',
		    fieldLabel: 'Hour',
		    displayField: 'hour',
		    valueField: 'index',
		    //renderTo: 'simpleCombo',
		    //displayField: 'size',
		    width: 100,
		    labelWidth: 30,
		    margin: '0 0 0 20',
		    store: hourStore,
		    queryMode: 'local',
		    //typeAhead: true,
		    //forceSelection: true
		    allowBlank : false,
		    editable: false,
		    value: 0,
		    listeners:{
		         'change': function(pgCmb, newValue, oldValue, eOpts) {
		        	 store.loadPage(1, {callback: callback});
		         }
		    }
		});
		
		Ext.define('hourlyFraudSummary', {
		     extend: 'Ext.data.Model',
		     fields: [
		         {name: 'id'},
		         {name: 'trafficDate'},
		         {name: 'trafficHour'},
		         {name: 'source'},
		         {name: 'msisdn'},
		         {name: 'imsi'},
		         {name: 'cellId'},
		         {name: 'lac'},
		         {name: 'imei'},
		         {name: 'vendor'},
		         {name: 'model'  },
		         {name: 'illegalOdds7Days'},
		         {name: 'illegalOdds24Hours'},
		         {name: 'callsOut'},
		         {name: 'bCount'},
		         {name: 'bRatio'},
		         {name: 'b2Out'},
		         {name: 'b2Ratio'},
		         {name: 'avgDur' },
		         {name: 'offPeak'},
		         {name: 'bursting'},
		         {name: 'cells'},
		         {name: 'callsIn'},
		         {name: 'smsOut'},
		         {name: 'smsIn'},
		         {name: 'clir'},
		         {name: 'audit'},
		         {name: 'verify'},
		         {name: 'seconds'},
		         {name: 'units'},
		         {name: 'possibleLoss'},
		         {name: 'handsetOrModule'},
		         {name: 'msisdnF'},
		         {name: 'imsiF'},
		         {name: 'imeiF'},
		         {name: 'cellIdF'},
		     ]
		});
		
		var store = Ext.create('Ext.data.Store', {
			//baseParams: { selDate: '2011-02-22' },
			//pageSize: 10,
			model: 'hourlyFraudSummary',
			
			proxy: {
			    type: 'ajax',
			    url: 'hourlyFraudSummary.action',
			    //url: "gridtest.json",
			    reader: {
			        type: 'json',
			        totalProperty: 'total',
			        root: 'root'
			    }
			}
		 	//autoLoad: true
		});
		
		store.on('beforeload', function (store, options) {
	        var new_params = { 
	        		selDate: Ext.getCmp('df').getRawValue(), 
	        		selHour: Ext.getCmp('hourCmb').getRawValue(), 
	        		total: store.getTotalCount() 
	        };
	        Ext.apply(store.proxy.extraParams, new_params);
	        Ext.getCmp("gridForm").getEl().mask("Loading");
	        // alert('beforeload');
	    });
		
		var dateField = Ext.create('Ext.form.DateField', {
	        //xtype: 'datefield',
	        id: 'df',
	        anchor: '1%',
	        fieldLabel: 'Day',
	        labelWidth: 30,
	        width: 150,
	        name: 'from_date',
	        //maxValue: new Date(),  // limited to the current date or prior
		    format: 'Y-m-d',
		    editable: false,
		    //previousDate: '',
		    listeners: {
		    	"select": function(dataPicker,date,eOpts ) {
			    	hourStore.load({callback: hourCallback});
		    	}
			}
		});
		
	    function msisdnRenderer(val,meta,rec,row,col) {
	    	var cls;
	        if (rec.get('msisdnF') == 1) {
	            cls='hotimeis';
	        } else {
	            cls='colLnk';
	        }
	        var res = "<a href='javascript:void(0);' onclick=\"popupWnd("+row+",'msisdn');\" class='"+cls+"'>" + val + '</a>';
	        return res;
	    }
	    
	    function imsiRenderer(val,meta,rec,row,col) {
	    	var cls;
	        if (rec.get('imsiF') == 1) {
	            cls='hotimeis';
	        } else {
	            cls='colLnk';
	        }
	        var res = "<a href='javascript:void(0);' onclick=\"popupWnd("+row+",'imsi');\" class='"+cls+"'>" + val + '</a>';
	        return res;
	    }
	    
	    function cellIdRenderer(val,meta,rec,row,col) {
	    	var cls;
	        if (rec.get('cellIdF') == 1) {
	            cls='hotimeis';
	        } else {
	            cls='colLnk';
	        }
	        var res = "<a href='javascript:void(0);' onclick=\"popupWnd("+row+",'cellId');\" class='"+cls+"'>" + val + '</a>';
	        return res;
	    }
	    
	    function imeiRenderer(val,meta,rec,row,col) {
	    	var cls="";
	        if (rec.get('imeiF') == 1) {
	            cls='hotimeis';
	        } else {
	            //cls='colLnk';
	        }
	        var res = "<span class='"+cls+"'>" + val + '</span>';
	        return res;
	    }
	    
	    function pctRenderer(val,meta,rec,row,col) {
	    	return Math.round(val*100)+"%";
	    }
		
		var gridPanel = Ext.create('Ext.grid.Panel', {
			id: 'gp',
			//columnWidth : 0.60,
	        columnLines: true,
			//loadMask: true,
			//xtype : 'gridpanel',
			//store : ds,
	        store: store,
	        width: '100%',
			height : '100%',
			//layout: 'anchor',
			//title : 'daily fraud summary',
			columns: [
			    {
					text: 'ID',
					dataIndex: 'id',
					width: 70,
					sortable : true
				},{
					text: 'Traffic Date',
					dataIndex: 'trafficDate',
					width: 70,
					sortable : true
				},{
					text: 'Traffic Hour',
					dataIndex: 'trafficHour',
					width: 70,
					sortable : true
				},{
					text: 'Source',
					dataIndex: 'source',
					width: 70,
					sortable : true
				},{
					text: 'MSISDN',
					dataIndex: 'msisdn',
					renderer: msisdnRenderer,
					sortable : true
				},{
					text: 'IMSI',
					dataIndex: 'imsi',
					renderer: imsiRenderer,
					width: 120,
					sortable : true
				},{
					text: 'Cell ID',
					dataIndex: 'cellId',
					renderer: cellIdRenderer,
					width: 70,
					sortable : true
				},{
					text: 'LAC',
					dataIndex: 'lac',
					width: 70,
					sortable : true
				},{
					text: 'IMEI',
					dataIndex: 'imei',
					renderer: imeiRenderer,
					sortable : true
				},{
					text: 'Vendor',
					dataIndex: 'vendor',
					width: 70,
					sortable : true
				},{
					text: 'Model',
					dataIndex: 'model',
					width: 70,
					sortable : true
				},{
					text: 'H/M',
					dataIndex: 'handsetOrModule',
					width: 70,
					sortable : true
				},{
					text: 'Illegal Odds 7 days',
					dataIndex: 'illegalOdds7Days',
					renderer: pctRenderer,
					width: 70,
					sortable : true
				},{
					text: 'Illegal Odds 24 hrs',
					dataIndex: 'illegalOdds24Hours',
					renderer: pctRenderer,
					width: 70,
					sortable : true
				},{
					text: 'Calls Out',
					dataIndex: 'callsOut',
					width: 70,
					sortable : true
				},{
					text: 'B Count',
					dataIndex: 'bCount',
					width: 70,
					sortable : true
				},{
					text: 'B Ratio',
					dataIndex: 'bRatio',
					width: 70,
					sortable : true
				},{
					text: 'Num Out Adjusted',
					dataIndex: 'b2Out',
					width: 70,
					sortable : true
				},{
					text: 'Num Ratio Adjusted Ratio',
					dataIndex: 'b2Ratio',
					width: 70,
					sortable : true
				},{
					text: 'Avg Dur',
					dataIndex: 'avgDur',
					width: 70,
					sortable : true
				},{
					text: 'Off Peak',
					dataIndex: 'offPeak',
					renderer: pctRenderer,
					width: 70,
					sortable : true
				},{
					text: 'Bursting',
					dataIndex: 'bursting',
					width: 70,
					sortable : true
				},{
					text: 'Cells',
					dataIndex: 'cells',
					width: 70,
					sortable : true
				},{
					text: 'Calls In',
					dataIndex: 'callsIn',
					width: 70,
					sortable : true
				},{
					text: 'SMS Out',
					dataIndex: 'smsOut',
					width: 70,
					sortable : true
				},{
					text: 'SMS In',
					dataIndex: 'smsIn',
					width: 70,
					sortable : true
				},{
					text: 'CLIR',
					dataIndex: 'clir',
					width: 70,
					sortable : true
				},{
					text: 'Audit',
					dataIndex: 'audit',
					sortable : true
				},{
					text: 'Verify',
					dataIndex: 'verify',
					width: 70,
					sortable : true
				},{
					text: 'Seconds',
					dataIndex: 'seconds',
					width: 70,
					sortable : true
				},{
					text: 'Units',
					dataIndex: 'units',
					width: 70,
					sortable : true
				},{
					text: 'Possible Loss',
					dataIndex: 'possibleLoss',
					width: 70,
					sortable : true
				}
				
			],
	        // paging bar on the bottom
	        bbar: Ext.create('Ext.PagingToolbar', {
	        	//pageSize:10,
	            store: store,
	            displayInfo: true,
	            displayMsg: 'Displaying Data {0} - {1} of {2}',
	            emptyMsg: "No Data",
	            listeners: {'change': function(comp, eOpts ) {
	            	Ext.getCmp("gridForm").getEl().unmask();
	            }}
	        })
		});
		
		var sevenBtn=Ext.create('Ext.Component', {
			html: "<a href='javascript:void(0);' onclick='javascript:showWeekly();'><img class='export_icon' style='width:23px;height:23px;' title='weekly' src='css/images/20097.jpg'></a>"
		});
		
		var mapBtn=Ext.create('Ext.Component', {
			html: "<a href='javascript:void(0);' onclick='javascript:showMap();'><img class='export_icon' style='margin-left:30px;width:24px;height:24px;' title='map' src='css/images/google-earth-icon.png'></a>"
		});
		
		var pdfBtn=Ext.create('Ext.Component', {
			html: "<a href='javascript:void(0);' onclick=\"javascript:exportFile(\'pdf\');\" ><img class='export_icon' style='width:23px;height:23px;' title='pdf' src='css/images/pdf.png'></a>"
		});
		
		var excelBtn=Ext.create('Ext.Component', {
			html: "<a href='javascript:void(0);' onclick=\"javascript:exportFile(\'xlsx\');\" ><img class='export_icon' title='excel' src='css/images/excel.png'></a>"
		});
		
		var csvBtn=Ext.create('Ext.Component', {
			html: "<a href='javascript:void(0);' onclick=\"javascript:exportFile(\'csv\');\" ><img class='export_icon' title='csv' src='css/images/csv.png'></a>"
		});
		
		function hideExportIcon() {
			pdfBtn.hide();
			excelBtn.hide();
			csvBtn.hide();
		}
		
		function showExportIcon() {
			pdfBtn.show();
			excelBtn.show();
			csvBtn.show();
		}
		
		var fieldsPanel = Ext.create('Ext.container.Container', {
			layout: {
				type: 'hbox',
				align: 'fit',
				padding: 5
			},
			items: [dateField, hourCombo, pageSizeCombo, pdfBtn, excelBtn, csvBtn]
		});
		
		var gridForm = Ext.create('Ext.form.Panel', {
			id : 'gridForm',
			frame : true,
			title : 'Hourly Fraud Summary',
			//bodyPadding : 5,
			//width : '100%',
			layout: {
		        type: 'vbox',       // Arrange child items vertically
		        align: 'stretch',    // Each takes up full width
		        padding: 5
		    },
			fieldDefaults : {
				labelAlign : 'left',
				msgTarget: 'side'
			},
			items: [fieldsPanel, gridPanel],
			renderTo : bd
		});
		//gridForm.child('gridpanel').getSelectionModel().select(0);
		var today=new Date();
		Ext.getCmp('df').setValue(today);
		//$('input[name=selDate]').val(store.baseParams.selDate);
		store.pageSize=pageSizeCombo.getValue();
		dateField.fireEvent('select');
		
		window.onresize=function() {
			gridForm.doLayout();
		};
	});
	
	String.prototype.replaceAll  = function(s1,s2){   
		return this.replace(new RegExp(s1,"gm"),s2);   
	};  
	
	function showWeekly() {
		parent.addTab('weeklyFraudSummary.jsp', 'Fraud Summary Weekly');
	}
	
	function showMap() {
		parent.addTab('mapsView.jsp', 'Map');
	}
	
	function exportFile(suffix) {
		var selDate=Ext.getCmp("df").getRawValue();
		var selHour=Ext.getCmp("hourCmb").getRawValue();
		window.open("export?bQuery=H&fileName=hourly_fraud_summary_report_" + selDate + selHour + "." + suffix);
	}
	
	function popupWnd(row,colType) {
		var model=Ext.getCmp('gp').getStore().getAt(row);
		var url;
		//var queryType;
		if(colType=='msisdn') {
			url='dailyFraudDetail!beforeExecute.action';
			//queryType=1;
		} else if(colType=='imsi') {
			url="dailyFraudDetail!beforeExecute.action";
			//queryType=1;
		} else if(colType=='cellId') {
			url="cellIdLocation.jsp";
			//queryType=3;
		} else {
			return;
		}
		var trafficDate=model.get("trafficDate");
		var msisdn=model.get("msisdn");
		var imsi=model.get("imsi");
		var cellId=model.get("lac")+''+model.get("cellId");
		var param="?selDate="+trafficDate+"&msisdn="+msisdn+"&imsi="+imsi+"&cellId="+cellId;
		//var bean=JSON.parse(beanStr);
		//alert("url="+url+", trafficDate="+trafficDate+", msisdn="+msisdn+", imsi="+imsi+", "+cellId);
		window.open(url+param, 'fraudDetailWindow','height=700, width=1000, top=0, left=150, toolbar=no,menubar=yes, scrollbars=no, resizable=no,location=no,status=no');
	}

</script>
<title>gridtest</title>
</head>
<body>
	<div id="demo"></div>
	<div id="grid-example"></div>
</body>
</html>